<?php

namespace app\listener;


use app\data\model\DataUser;
use app\mall_back\model\GoodsLuckyDrawModel;
use app\mall_back\model\TescoRecordModel;

class RobotsFilling
{
    /**
     * @param GoodsLuckyDrawModel $edata
     *
     * @return void
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($edata)
    {
        $i = 0;
        while ($i < $edata['participants_number']) {
            $user = $this->random_user($edata['choice_robots']);

            $data = [
                'u_id'                => $user['id'],
                'goods_id'            => $edata['goods_id'],
                'goods_lucky_draw_id' => $edata['id'],
                'add_ress_id'         => 0,
                'lucky_number'        => random_int(195782, 995782),
                'create_time'         => date('Y-m-d H:i:s'),
            ];
            TescoRecordModel::insert($data);
            $i++;
        }
    }

    public function random_user($robotIds = '')
    {
        static $robots = NULL;
        if (!$robots) {
            if (!empty($robotIds)) {
                $robotIds = explode(',', $robotIds);
                $robots = DataUser::where('id', 'IN', $robotIds)->where('is_bot', 1)->select();
            } else {
                $robots = DataUser::where('is_bot', 1)->select();
            }

            $robots = $robots->toArray();
        }

        $length = count($robots);
        srand(microtime(TRUE));

        return $robots[random_int(1, $length - 1)];
    }
}